package net.sinmetal.twitcockpit.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SecurityUtil
 *
 * @author Sinmetal
 *
 */
public class SecurityUtil {

    public static String encrypt(String value) {
        return encrypt(StringUtil.toByte(value));
    }

    public static String encrypt(byte[] value) {
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }
        sha.update(value);

        return hashByte2String(sha.digest());
    }

    /**
     * 16進数に変換
     *
     * @param hash
     * @return
     */
    private static String hashByte2String(byte[] hash) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < hash.length; i++) {
            if ((0xff & hash[i]) < 0x10) {// < 16（<=F）の場合、1桁になるので、頭に"0"を追加
                hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); // HEX
            } else {
                hexString.append(Integer.toHexString(0xFF & hash[i])); // HEX
            }
        }

        return hexString.toString();
    }
}
